#include "blockQueue.hpp"
#include "Task.hpp"
#include <unistd.h>
#include <ctime>


void *Productor(void* args)
{
    blockQueue<Task> *bq = static_cast<blockQueue<Task> *>(args);    
    int len = OP.size();
    while (true)
    {
        // 模拟生产者生产数据
        int data1 = rand() % 10 + 1; // [1,10]
        usleep(10);
        int data2 = rand() % 10;
        char op = OP[rand() % len];
        Task t(data1, data2, op);

        // 生产
        bq->push(t);
        std::cout << "生产了一个任务: " << t.GetTask() << " thread id: " << pthread_self() << std::endl;
        sleep(1);
    }
    
    return nullptr;

}

void *Consumer(void* args)
{
    blockQueue<Task> *bq = static_cast<blockQueue<Task> *>(args);

    //消费
    while(true)
    {
        Task t = bq->pop();//消费

        t.run();

        std::cout << "处理任务: " << t.GetTask() << " 运算结果是： " << t.GetRes() << " thread id: " << pthread_self() << std::endl;

    }

    return nullptr;
}

int main()
{
    srand(time(nullptr));
    blockQueue<Task> *bq = new blockQueue<Task>;
    pthread_t c[3],p[5];
    
    for(int i = 0; i < 3; i++)
        pthread_create(c+i,nullptr,Consumer,bq);
    
    for(int i = 0; i < 5; i++)
        pthread_create(p+i,nullptr,Productor,bq);

    for(int i = 0; i < 3; i++)
        pthread_join(c[i],nullptr);
    for(int i = 0; i < 5; i++) 
        pthread_join(p[i],nullptr);

    delete bq;
    return 0;
}

